<template>
    <el-upload v-model:file-list="fileList" action="#" list-type="picture-card" 
    :limit="limit"
    :on-preview="handlePictureCardPreview" 
    :on-remove="handleRemove"
    :before-upload="beforeUpload"
    :http-request="submitUpload"
    :on-exceed="handleExceed"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
  
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image"  style="width: 100%;"/>
    </el-dialog>
  </template>

  <script lang="ts" setup>
  import { ref,watchEffect,onMounted } from 'vue'
  import { Plus } from '@element-plus/icons-vue'
  import type { UploadProps, UploadUserFile } from 'element-plus'
  import { uploadFile } from '@/api/system/upload'
  import { ElMessage } from 'element-plus'
  const emit = defineEmits(['updateInfo'])
  const props = defineProps({
    urlList: {
            type: Array,
            default: () => {
                return []
            }
        },
    type:{ //可上传附件类型
            type: String,
            default: 'jpg'
        },
    fileSize: { // 上传文件大小 单位M
            type: Number,
            default: 1
        },
    limit: { // 最大上传文件数
            type: Number,
            default: 1
        },
    })
// 文件上传前
const beforeUpload = (file) => {
    const typeList = props.type.split("/").map(item => {
        if(item == 'pdf'){
            return 'application/pdf'
        }else if(item == 'xls'){
            return 'application/vnd.ms-excel'
        }else if(item == 'xlsx'){
            return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        }else if(item == 'doc'){
            return 'application/msword'
        }else if(item == 'docx'){
            return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        }else if(item == 'zip'){
            return 'application/zip'
        }else{
            return  `image/${item}`
        }
    })
    const flieM = file.size / 1024 / 1024 //字节转为M
    if(flieM > props.fileSize){
        ElMessage.warning("文件大小不能超过" + props.fileSize + "M")
        return false
    }else if(!typeList.includes(file.type)){ 
        ElMessage.warning("此文件格式禁止上传")
        return false;
    }
    return true; // 返回 true 表示通过校验，继续上传
    // else{
    //     submitUpload(file)
    // }
}
const fileList = ref([])
//上传文件
const submitUpload = async (value) => {
    const formData = new FormData();
    formData.append('file', value.file);
    try {
        await uploadFile(formData).then((res) =>{
            fileList.value.push(res.data); // 更新文件列表
            fileList.value = fileList.value.filter((file) => !file.url.startsWith('blob:'));
            emit('updateInfo',fileList.value)
            value.onSuccess(res); // 通知组件上传成功
        });
    } catch (err) {
        value.onError(err); // 通知组件上传失败
    }
}
 // 文件超出限制时
 const handleExceed = (files, fileList) => {
        ElMessage.warning(`最多添加${props.limit}个附件`)
    }



watchEffect(() => {
      fileList.value = props.urlList
})
onMounted(()=>{
    try{
        fileList.value = JSON.parse(props.urlList)
    }catch(err){
    }  
})

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => { //删除图片
//     console.log(uploadFile, uploadFiles)
// }
const handleRemove = (file) => {
        const newFile =  fileList.value.filter(item => item.uid != file.uid)
        emit('updateInfo',newFile)
        fileList.value = newFile
    }
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {  // 图片预览
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

</script>